package com.wolf.gulimall.seckill.interceptor;

import com.wolf.common.constant.AuthServerConstant;
import com.wolf.common.vo.MemberEntityVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户登录拦截器
 */
@Component
public class LoginUserInterceptor implements HandlerInterceptor {

    public static ThreadLocal<MemberEntityVo> loginUser = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // /kill请求需要进行登录验证
        boolean match = new AntPathMatcher().match("/kill", request.getRequestURI());
        if (match) {
            MemberEntityVo attribute = (MemberEntityVo) request.getSession().getAttribute(AuthServerConstant.LOGIN_USER);
            if (attribute != null) {
                //将用户信息储存到本地线程变量中,以便后续操作获取
                loginUser.set(attribute);
                return true;
            } else {
                //没有登录的用户需要进行登录才能访问
                request.getSession().setAttribute("msg", "请先登录!");
                response.sendRedirect("http://auth.gulimallwolf.com/login.html");
                return false;
            }
        }
        return true;
    }
}
